package com.zdy.im.user.service.impl;


import com.sixeco.framework.common.data.BasePage;
import com.sixeco.framework.common.enums.ResultEnum;
import com.sixeco.framework.core.db.ext.Query;
import com.sixeco.framework.http.data.vo.ResponseResultList;
import com.sixeco.framework.http.exception.SystemRuntimeException;
import com.sixeco.framework.util.PageUtils;
import com.sixeco.framework.util.excel.ExcelUtils;
import com.zdy.im.chat.ChatMessageEnum;
import com.zdy.im.enums.ImMessageTypeEnum;
import com.zdy.im.enums.ImResultCodeEnum;
import com.zdy.im.user.dao.ImMessageReadDao;
import com.zdy.im.user.dto.request.ImChatReadStatusRequestDto;
import com.zdy.im.user.dto.request.ImMessageReadRequestDto;
import com.zdy.im.user.entity.ImMessageRead;
import com.zdy.im.user.service.ImChatMessageService;
import com.zdy.im.user.dto.response.ImChatMessageResponseDto;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;


import com.zdy.im.user.entity.ImChatMessage;
import com.zdy.im.user.dao.ImChatMessageDao;
import com.zdy.im.user.dto.request.ImChatMessageRequestDto;

import java.io.InputStream;


/**
 * @ClassName: ImChatMessageDao.java
 * @Description: 的数据交互处理类
 * @Author 作者 : zdy
 * @CreateDate 创建时间: 2021-02-30
 * @version V1.0.0
 * <p>
 * ----------------------------------------------------------------------------
 *  modifyer    modifyTime                 comment
 *
 * ----------------------------------------------------------------------------
 * </p>
 */
@Service
public class ImChatMessageServiceImpl  implements ImChatMessageService {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private ImChatMessageDao  imChatMessageDao;

    @Autowired
    private ImMessageReadDao imMessageReadDao;

    /**
     * 保存同时更新数据库和缓存的实现方法
     * @param imChatMessageRequestDto ImChatMessageResponseDto
     * @return
     */
    @Override
    public ImChatMessageResponseDto saveImChatMessage(ImChatMessageRequestDto imChatMessageRequestDto){
        if(imChatMessageRequestDto== null){
            return null;
        }
        ImChatMessage imChatMessage = ImChatMessage.build().clone(imChatMessageRequestDto);

        boolean result = imChatMessageDao.save(imChatMessage);
        if(!result){
            return null;
        }
        ImChatMessageResponseDto imChatMessageResponseDto = ImChatMessageResponseDto.build().clone(imChatMessage);
        return imChatMessageResponseDto;


    }

    @Override
    public boolean saveBatchImChatMessage(Collection<ImChatMessageRequestDto> entityList, int batchSize) {
        if(null == entityList || entityList.size() !=  batchSize){
            return false;
        }
        List<ImChatMessage> list = new ArrayList<>();
        entityList.forEach(e -> list.add(ImChatMessage.build().clone(e)));
        boolean result = imChatMessageDao.saveBatch(list,batchSize);
        return result;
    }

    @Override
    public boolean saveOrUpdateBatchImChatMessage(Collection<ImChatMessageRequestDto> entityList, int batchSize) {
        if(null == entityList || entityList.size() != batchSize ){
            return false;
        }
        List<ImChatMessage> list = new ArrayList<>();
        entityList.forEach(e -> list.add(ImChatMessage.build().clone(e)));
        boolean result = imChatMessageDao.saveOrUpdateBatch(list,batchSize);
        return result;
    }

    @Override
    public boolean updateBatchById(Collection<ImChatMessageRequestDto> entityList, int batchSize) {
        if(null == entityList || entityList.size() != batchSize ){
            return false;
        }
        List<ImChatMessage> list = new ArrayList<>();
        entityList.forEach(e -> list.add(ImChatMessage.build().clone(e)));
        boolean result =  imChatMessageDao.updateBatchById(list,batchSize);
        return result;
    }

    /**
     * 更新同时更新数据库和缓存的实现方法
     * @param imChatMessageRequestDto  ImChatMessageResponseDto
     * @return
     */
    @Override
    public boolean updateImChatMessage(ImChatMessageRequestDto imChatMessageRequestDto){

          if(null ==  imChatMessageRequestDto){
              return false;
          }

        ImChatMessage imChatMessage = ImChatMessage.build().clone(imChatMessageRequestDto);

        return imChatMessageDao.updateById(imChatMessage);


    }


    /**
     * 更新消息的是否已读状态数据库和缓存的实现方法
     * @param statusRequestDto  ImChatReadStatusRequestDto
     * @return
     */
    @Override
    public boolean updateImChatMessageReadStatus(ImChatReadStatusRequestDto statusRequestDto){
        if(statusRequestDto == null || statusRequestDto.getMessageId() < 0 ){
            return false;
        }
        ImChatMessage imChatMessage =  imChatMessageDao.getById(statusRequestDto.getMessageId());
        if(imChatMessage == null){
            return false;
        }
        if(statusRequestDto.getSendUserId() != imChatMessage.getSendUserId()
                || statusRequestDto.getToUserId() != imChatMessage.getToId()){
            throw new SystemRuntimeException(ImResultCodeEnum.IM_MESSAGE_NOT_EXIST);
        }
        ChatMessageEnum messageEnum = ChatMessageEnum.getEnum( statusRequestDto.getReadType());
        imChatMessage.setReadStatus(messageEnum.getDbValue());
        imChatMessageDao.updateById(imChatMessage);
        return true;
    }




    /**
     * 通过主键ID删除对象信息实现缓存和数据库,同时删除的方法
     * @param  idList
     * @return
     */
    @Override
    public int delImChatMessageByIds(List<Long> idList){
        boolean result = false;
        if(null == idList){
            return ResultEnum.FAIL.id();
        }
        if( idList.size() == 1) {
            result = imChatMessageDao.removeById(idList.get(0));
        }else {
            result =  imChatMessageDao.removeByIds(idList);
        }
        if(result){
            return ResultEnum.SUCCESS.id();
        }
        return ResultEnum.FAIL.id();

    }


    /**
     * 通过主键ID更新对象实现缓存和数据库更新的方法
     * @param  imChatMessageId
     * @return
     */
    @Override
    public ImChatMessageResponseDto getImChatMessageById(long imChatMessageId){
        if(imChatMessageId < 0 ){
            return null;
        }
        ImChatMessage imChatMessage =  imChatMessageDao.getById(imChatMessageId);
        if(imChatMessage == null){
            return null;
        }
        ImChatMessageResponseDto imChatMessageResponseDto = ImChatMessageResponseDto.build().clone(imChatMessage);

        return imChatMessageResponseDto ;

    }

    @Override
    public List<ImChatMessageResponseDto> getImChatMessageByPage(BasePage page) {
        return null;
    }


    /**
    * 查询条件
    */
    public QueryWrapper<ImChatMessage> checkQueryCondition(BasePage basePage) {
        QueryWrapper<ImChatMessage> queryWrapper = new QueryWrapper<>();
        ImChatMessageRequestDto imChatMessageRequestDto = (ImChatMessageRequestDto) basePage.getParamObject();

                                                                                                                                                                                                                                                                                                                                                return queryWrapper;
    }


    /**
     * 通过分页获取ImChatMessage信息实现查找缓存和数据库的方法
     * @param basePage BasePage
     * @return
     * @author suven
     * @date 2021-05-12 17:26:13
     */
    @Override
    public List<ImChatMessageResponseDto> getImChatMessageByPage(
            ResponseResultList<ImChatMessageResponseDto> responseResultList, BasePage basePage){
         List<ImChatMessageResponseDto> list =
                 imChatMessageDao.getImChatMessageByPage(responseResultList,basePage);
        return list;

    }

    /**
     * 通过分页获取ImChatMessage信息实现查找缓存和数据库的方法
     * @param basePage BasePage
     * @return
     * @author suven
     * @date 2021-05-12 17:26:13
     */
    @Override
    public ResponseResultList<ImChatMessageResponseDto> getImChatMessageByUserIdToIdPage(BasePage basePage){
        List<ImChatMessageResponseDto>  list = imChatMessageDao.getImChatMessageByUserIdToIdPage(basePage);
        if(null == list ){
            list = new ArrayList<>();
        }
        ImChatMessageRequestDto imChat = (ImChatMessageRequestDto) basePage.getParamObject();
        ImMessageReadRequestDto im = ImMessageReadRequestDto.build().toUserId(imChat.getSendUserId())
                .toMessageId(imChat.getToId()).toType(ImMessageTypeEnum.Single.getKey());
        ImMessageRead imMessageRead = imMessageReadDao.getImMessageReadByUser(im);

        long readMessageId = 0;
        if(imMessageRead != null){
            readMessageId = imMessageRead.getGlobalId();
        }
        long finalReadMessageId = readMessageId;
        list.forEach(dto ->{
            int  readStatus = 1;//默认已读状
            if(dto.getGlobalId() > finalReadMessageId){
                readStatus = 0;//未读状态
            }
            dto.setReadStatus(readStatus);
        });
        ResponseResultList<ImChatMessageResponseDto> responseResultList =
                ResponseResultList.build(list,basePage.getRealPageSize());
        return responseResultList;

    }

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage iPage =  new Query<ImChatMessage>().getPage(params);
        QueryWrapper<ImChatMessage> queryWrapper = new QueryWrapper<>();
        IPage<ImChatMessage> page = imChatMessageDao.page(iPage,queryWrapper);
        return new PageUtils(page);
    }


    /**
     * 保存同时更新数据库和缓存的实现方法
     * @return
     */

    public ImChatMessage  setImChatMessage(){
        ImChatMessage imChatMessage = new ImChatMessage();
        /**
 			//imChatMessage.setSendUserId (String sendUserId);
 			//imChatMessage.setSendUserName (String sendUserName);
 			//imChatMessage.setSendUsrImg (String sendUsrImg);
 			//imChatMessage.setSendTime (Date sendTime);
 			//imChatMessage.setServiceTime (Date serviceTime);
 			//imChatMessage.setMessageId (long messageId);
 			//imChatMessage.setGlobalId (long globalId);
 			//imChatMessage.setMessageType (int messageType);
 			//imChatMessage.setContent (String content);
 			//imChatMessage.setContentImg (String contentImg);
 			//imChatMessage.setContentVideo (String contentVideo);
 			//imChatMessage.setMine (int mine);
 			//imChatMessage.setToId (String toId);
 			//imChatMessage.setToUserName (String toUserName);
 			//imChatMessage.setToUserImg (String toUserImg);
 			//imChatMessage.setReadStatus (int readStatus);
		**/

        return imChatMessage;
    }

    @Override
    public boolean saveData(InputStream initialStream) {
        return ExcelUtils.readExcel(initialStream,imChatMessageDao, ImChatMessage.class,0);
    }


}
